//
//  LoginViewController.swift
//  todoApp
//
//  Created by lili on 15/2/21.
//  Copyright (c) 2015年 ll studio. All rights reserved.
//

import UIKit
import MMDrawerController

class LoginViewController: UIViewController, WXApiDelegate,UISearchBarDelegate,UISearchDisplayDelegate,UITableViewDataSource,UITableViewDelegate{
    
    @IBOutlet var avtarImageView: UIImageView!
    @IBOutlet weak var qqBtn: UIButton!
    @IBOutlet weak var wechatBtn: UIButton!
    @IBOutlet weak var weiboBtn: UIButton!
    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var passwordField: UITextField!
    @IBOutlet weak var loginBtn: UIButton!
    @IBOutlet weak var registBtn: UIButton!
    @IBOutlet weak var userName: UILabel!
    
    //图片
    @IBOutlet weak var loginLabel: UILabel!
    @IBOutlet weak var loginLabel2: UILabel!
    @IBOutlet weak var mailPic: UIImageView!
    @IBOutlet weak var passwordPic: UIImageView!
    
    var searchBar:UISearchBar?
    var displayController:UISearchDisplayController?
    var toDoItems:NSMutableArray=NSMutableArray()
    var displayDataSource:NSMutableArray = NSMutableArray()
    
    var networking : NoteNetworkManager =  NoteNetworkManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
         //颜色
        self.view.backgroundColor=BACKGROUND_COLOR
        
        self.loginBtn.backgroundColor=BUTTON_COLOR
        //self.loginBtn.currentTitleColor=
        self.registBtn.backgroundColor=BUTTON_COLOR
        
        searchBar = UISearchBar(frame: CGRectMake(0, 20, CGRectGetWidth(self.view.bounds), 44))
        searchBar?.autocorrectionType = UITextAutocorrectionType.No
        searchBar?.autocapitalizationType = UITextAutocapitalizationType.None
        searchBar?.delegate = self
        searchBar?.hidden = true
        weiboBtn.hidden = true
        loginLabel2.hidden = true
        displayController = UISearchDisplayController(searchBar: searchBar!, contentsController: self.navigationController!)
        displayController!.delegate = self;//自身的
        self.navigationController?.view.addSubview(searchBar!)
        displayController!.searchResultsDataSource = self;//显示数据的代理
        displayController!.searchResultsDelegate = self;//对事件的代理
        displayController?.searchResultsTableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshView()
        self.wechatBtn.hidden = true
        self.qqBtn.hidden = true
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    func refreshView()
    {
        self.loginBtn.removeTarget(self, action: "loginButtonTapped", forControlEvents: UIControlEvents.TouchUpInside)
        self.loginBtn.removeTarget(self, action: "logoutAction", forControlEvents: UIControlEvents.TouchUpInside)
        
        if (NSUserDefaults.standardUserDefaults().boolForKey("isUserLoggedIn") == true)
        {
            //登录状态
            self.loginBtn.addTarget(self, action: "logoutAction:", forControlEvents: UIControlEvents.TouchUpInside)
            self.registBtn.hidden = true;
            self.loginBtn.setTitle("登  出", forState: UIControlState.Normal)
//            self.userName.hidden = false
            
            
            avtarImageView.image = UIImage(named: "register")
            loginLabel.hidden = true;
            loginLabel2.hidden = true;
            mailPic.hidden = true;
            passwordPic.hidden = true;
            
            var name:NSString! = NSUserDefaults.standardUserDefaults().objectForKey("acountName") as! NSString

            self.userName.text = NSString(format:"%@", name) as String
            for index  in self.view.subviews
            {
                var subView = index as! UIView
                
                if (subView.tag == 2)
                {
                    subView.hidden = true
                }
            }
            
            self.weiboBtn.hidden = true
            self.wechatBtn.hidden = true
            self.qqBtn.hidden = true
        }
        else
        {
            self.loginBtn.addTarget(self, action: "loginButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
            self.loginBtn.setTitle("登  录", forState: UIControlState.Normal)
            self.registBtn.hidden = false;
//            self.userName.hidden = true
            self.userName.text = ""
            for index  in self.view.subviews
            {
                var subView = index as! UIView
                
                if (subView.tag == 2)
                {
                    subView.hidden = false
                }
            }
            self.userName.text = "未登录"
            avtarImageView.image = UIImage(named: "noLogin")
            
            loginLabel2.hidden = true;
            self.weiboBtn.hidden = true
            
//            self.wechatBtn.hidden = false
//            self.qqBtn.hidden = false
            mailPic.hidden = false;
            passwordPic.hidden = false;
        }
    }
    @IBAction func upload(sender: UIButton) {
        if (NSUserDefaults.standardUserDefaults().boolForKey("isUserLoggedIn") == false)
        {
            UIAlertView.showWithTitle("请登录后使用上传功能", message: "", cancelButtonTitle: "确定", otherButtonTitles: [], tapBlock: nil)
            
            return;
        }
        var tmp = NSMutableArray(array: self.toDoItems)
        var uploadTmpArray = NSMutableArray()
        
        if  let results = self.downLoadNotesFromAVOS(self.userId())
        {
            for index in results
            {
                var avosObj:AVObject = index as! AVObject
                var noteId:NSString = avosObj.objectForKey("noteId") as! NSString
                
                for idx in self.toDoItems
                {
                    var note:NoteModel! = idx as! NoteModel
                    
                    if noteId.isEqualToString(note.noteId)
                    {
                        //遍历本地是否有此条目，有的话更新
                        uploadTmpArray.addObject(NSDictionary(objects: [avosObj,note], forKeys: ["avosObj","noteObj"]))
                        tmp.removeObject(note)
                    }
                }
            }
        }
        
        for index in tmp
        {
            var newNoteObj = AVObject(className: "NoteClass")
            uploadTmpArray.addObject(NSDictionary(objects: [newNoteObj,index], forKeys: ["avosObj","noteObj"]))
        }
        
        //self.showHudWithTitle("开始同步到服务器")
        self.startUploadData(0, uploadArray: uploadTmpArray)
    }
    
    func logoutAction(sender: UIButton){
        NSUserDefaults.standardUserDefaults().removeObjectForKey("isUserLoggedIn");
        NSUserDefaults.standardUserDefaults().removeObjectForKey("userAccount");
        NSUserDefaults.standardUserDefaults().removeObjectForKey("acountName");
        
        NSUserDefaults.standardUserDefaults().synchronize()
        
        self.refreshView()
    }
    
     func loginButtonTapped(sender: AnyObject) {
        
        self.view.endEditing(true)
        //TODO: 这里你需要本地验证输入
        let userEmail=emailField.text
        let userPassword=passwordField.text
        
        var emailLength:NSString? = emailField.text
        if (emailLength?.length == 0)
        {
            UIAlertView.showWithTitle("请输入用户名", message: "", cancelButtonTitle: "确定", otherButtonTitles: nil, tapBlock: nil)
            return
        }
        
        var avosQuery = AVQuery(className: "AccountClass");
        avosQuery.whereKey("userAccount", equalTo:emailField.text);
        
        self.mm_drawerController.showIndicatorWithContent("请稍后")
        
        var results : NSArray? = avosQuery.findObjects() as NSArray?;
        
        
        if (results != nil && results!.count>0)
        {
            var account:AVObject = results?.objectAtIndex(0) as! AVObject
            var pwd = account.objectForKey("userPassword") as! NSString
            
            if (pwd.isEqualToString(userPassword!))
            {
                //登陆成功
                self.loginSuccessForUser(userEmail!, userName: userEmail!)
            }
            else
            {
                self.mm_drawerController.hideIndicator()
                self.mm_drawerController.showHudWithTitle("密码错误")
            }
        }
        else
        {
            self.mm_drawerController.hideIndicator()

            NSUserDefaults.standardUserDefaults().removeObjectForKey("isUserLoggedIn");
            NSUserDefaults.standardUserDefaults().removeObjectForKey("userAccount");
            NSUserDefaults.standardUserDefaults().removeObjectForKey("acountName");
            NSUserDefaults.standardUserDefaults().synchronize()
            
            self.mm_drawerController.showHudWithTitle("账号不存在")
        }
    }
    
    func loginSuccessForUser(userAccount:String, userName: String)
    {
        NSUserDefaults.standardUserDefaults().setBool(true, forKey:"isUserLoggedIn")
        NSUserDefaults.standardUserDefaults().setObject(userAccount, forKey:"userAccount")
        NSUserDefaults.standardUserDefaults().setObject(userName, forKey:"acountName")
        
        NSUserDefaults.standardUserDefaults().synchronize()
        
        self.refreshView()

        self.canDownloadNotesForCurrentUser(userAccount)
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
        self.view.endEditing(true)
    }
    
    //如果用户第一次登录，且云端存在备份就从云端下载
    func canDownloadNotesForCurrentUser(username:NSString!)
    {
        var shouldDownload : Bool = true
        
        if let loggedUsers: NSArray = NSUserDefaults.standardUserDefaults().objectForKey("loggedUser") as? NSArray
        {
            loggedUsers.enumerateObjectsUsingBlock({ (name, index, stop) -> Void in

                var nameStr:NSString = name as! NSString
                if nameStr.isEqualToString(username! as String)
                {
                    shouldDownload = false
                }
            })
        }
        else
        {
            var set = NSMutableArray()
            set.addObject(username)
            NSUserDefaults.standardUserDefaults().setObject(set, forKey: "loggedUser")
        }
        
        let 融合云端数据 = {
            
            ()->() in
            
            if let results = self.downLoadNotesFromAVOS(username)
            {
                if (results.count>0)
                {
                    var tmpArr = NSMutableArray();
                    
                    results.enumerateObjectsUsingBlock({(obj, idx, stop) -> Void in
                        
                        var avobj = obj as! AVObject
                        var dic:NSMutableDictionary = avobj.dictionaryForObject() as NSMutableDictionary
                        
                        if (dic.objectForKey("localCreateTime") == nil)
                        {
                            var date = NSDate();
                            dic.setObject(NSNumber(double: date.timeIntervalSince1970), forKey: "localCreateTime")
                        }
//                        let noteObj = NoteModel(dictionary: dic as [NSObject : AnyObject], error:nil);
                        let noteObj = NoteModel(dictionary: dic as [NSObject : AnyObject]);
//                        noteObj.noteText = dic.valueForKey("noteText") as! String;
////                        if (dic.allKeys.contains("noteTag")){
////                            noteObj.noteTag = dic.valueForKey("noteTag") as! String;
////                        }
////                        
//                        noteObj.userId = dic.valueForKey("userId") as! String;
//                        noteObj.noteId = dic.valueForKey("noteId") as! String;
//                        noteObj.localCreateTime = dic.valueForKey("localCreateTime") as! NSTimeInterval;
                        
                        print(noteObj)
                        if (noteObj != nil)
                        {
                            tmpArr.addObject(noteObj)
                        }
                        
    
                    })
                    
                    //清理掉之前本地缓存的
                    NoteDBManger.shareInstance().deleteAllNotes()
                    
                    NoteDBManger.shareInstance().addNotes(tmpArr as [AnyObject])
                    
//                    self.navigationController?.popViewControllerAnimated(true)
                    NSNotificationCenter.defaultCenter().postNotificationName("downLoadNoteNotify", object: nil)

                }
                else{
//                    self.navigationController?.popViewControllerAnimated(true)
                }
            }
        }
        
        
        if (shouldDownload == false)
        {
            //不需要下载直接返回
            self.mm_drawerController.hideIndicator()
//            self.navigationController?.popViewControllerAnimated(true)
        }
        else
        {
            var avosQuery = AVQuery(className: "NoteClass");
            avosQuery.whereKey("userId", equalTo:username);
            
            var count :NSInteger =  avosQuery.countObjects();
            
            self.mm_drawerController.hideIndicator()
            if (count > 0)
            {
                融合云端数据();
//                UIAlertView.showWithTitle("是否同步云端数据", message:"", cancelButtonTitle: "否", otherButtonTitles: ["是"], tapBlock: { (alert, idx) -> Void in
//                    if (idx == 1)
//                    {
//                        融合云端数据();
//                    }
//                    else
//                    {
////                        self.navigationController?.popViewControllerAnimated(true)
//                    }
//                })
            }
            else
            {
//                self.navigationController?.popViewControllerAnimated(true)
            }
        }
    }
    
//    override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
//        
//        if (segue!.identifier=="toRegister")  {
//
//            var detailViewController:RegisterViewController=segue!.destinationViewController as! RegisterViewController
//    
//            detailViewController.completeBlk = {
//                ()->() in
//                self.refreshView()
//            }
//            
//        }
//        // Get the new view controller using [segue destinationViewController].
//        // Pass the selected object to the new view controller.
//    }
    
    
    @IBAction func loginWithQQ(sender: UIButton) {

        ShareSDK.getUserInfoWithType(ShareTypeQQSpace, authOptions: nil) { (result:Bool, userinfo:ISSPlatformUser!, error:ICMErrorInfo!) -> Void in
            if(result)
            {
                let uid=userinfo.uid()
                let nickname=userinfo.nickname()
                
                //用户头像
                //let profileImage=userinfo.profileImage()
                
                UIAlertView.showWithTitle("", message: ("授权登录成功,用户id:\(uid),用户昵称:\(nickname)"), cancelButtonTitle: "确定", otherButtonTitles: [], tapBlock: nil)
                self.shouldRegistForThirdPartLogin(uid, userName: nickname)
                print("ok")
            }
            else
            {
                print("分享失败,错误码:")
                print(error.errorCode())
                print(error.errorDescription())
                if error.errorCode() == -6004
                {
                    UIAlertView.showWithTitle("请先安装QQ客户端", message: "", cancelButtonTitle: "ok", otherButtonTitles: nil, tapBlock: nil)
                }
            }
        }
    }

    
    @IBAction func loginWithWechat(sender: UIButton) {
        //添加微信第三方登陆代码
        
        /*var req : SendAuthReq! = SendAuthReq()
        req.scope = "snsapi_userinfo"
        var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.wechatHandleDelegate = self
        
        WXApi.sendAuthReq(req, viewController: self, delegate: self)
*/
//        ShareSDK.getUserInfoWithType(ShareTypeWeixiSession, authOptions: nil, result:{ (result:BOOL, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error))
        ShareSDK.getUserInfoWithType(ShareTypeQQSpace, authOptions: nil) { (result:Bool, userinfo:ISSPlatformUser!, error:ICMErrorInfo!) -> Void in
            if(result)
            {
                let uid=userinfo.uid()
                let nickname=userinfo.nickname()
                
                 //用户头像
                 //let profileImage=userinfo.profileImage()
                
                UIAlertView.showWithTitle("", message: ("授权登录成功,用户id:\(uid),用户昵称:\(nickname)"), cancelButtonTitle: "确定", otherButtonTitles: [], tapBlock: nil)
                self.shouldRegistForThirdPartLogin(uid, userName: nickname)
                print("ok")
            }
            else
            {
                print("分享失败,错误码:")
                print(error.errorCode())
                print(error.errorDescription())
            }
        }
    }
   
    //wechat delelgate
    func onResp(resp: BaseResp!) {
        
        if resp.isKindOfClass(SendAuthResp)
        {
            var authResp : SendAuthResp = resp as! SendAuthResp
            
            var code = authResp.code
            
            if let code = authResp.code
            {
                //通过code获取accessToken
                var url = NSString(format: "https://api.weixin.qq.com/sns/oauth2/access_token?appid=1403638662&secret=ea4d8cbd7525cce0583e1220b6a5849f&code=%@&grant_type=authorization_code", code)
                weak var wSelf = self
                
                self.networking.getContentAtURL(url as String, param: nil, errorHandler: { (err) -> Void in
                    wSelf?.showHudWithTitle("登录失败")
                    }, successHandler: { (data) -> Void in
                        
                        if let ret = data as? NSDictionary
                        {
                            if let accessToken = ret.objectForKey("access_token") as? String
                            {
                                var openId = ret.objectForKey("openid") as! String
                                self.shouldRegistForThirdPartLogin(openId, userName: openId)
                            }
                            else
                            {
                                wSelf?.showHudWithTitle("登录失败")
                            }
                        }
                        else
                        {
                            wSelf?.showHudWithTitle("登录失败")
                        }
                })
            }
        }
    }
    
    @IBAction func loginWithWeibo(sender: UIButton) {
        
        ShareSDK.getUserInfoWithType(ShareTypeSinaWeibo, authOptions: nil) { (result:Bool, userinfo:ISSPlatformUser!, error:ICMErrorInfo!) -> Void in
            if(result)
            {
                let uid=userinfo.uid()
                let nickname=userinfo.nickname()
                
                //用户头像
                //let profileImage=userinfo.profileImage()
                
                UIAlertView.showWithTitle("", message: ("授权登录成功,用户id:\(uid),用户昵称:\(nickname)"), cancelButtonTitle: "确定", otherButtonTitles: [], tapBlock: nil)
                self.shouldRegistForThirdPartLogin(uid, userName: nickname)
                print("ok")
            }
            else
            {
                print("分享失败,错误码:")
                print(error.errorCode())
                print(error.errorDescription())
            }
        }

        
        
//        //添加微博第三方登陆代码
//        var request : WBAuthorizeRequest = WBAuthorizeRequest.request() as! WBAuthorizeRequest
//        request.redirectURI = "https://api.weibo.com/oauth2/default.html"
//        request.scope = "all"
//        var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//        appDelegate.wbHandleDelegate = self
//
//        WeiboSDK.sendRequest(request)
    }
    
    func shouldRegistForThirdPartLogin(userid: String, userName: String)
    {
        if (self.alreadyExistAccount(userid))
        {
            self.loginSuccessForUser(userid, userName: userName)
        }
        else
        {
            var accountObj = AVObject(className: "AccountClass")
            accountObj.setObject(userid, forKey: "userAccount")
            accountObj.setObject(userName, forKey: "acountName")
            accountObj.setObject(true, forKey: "isThirdPartLogin")
            self.showIndicatorWithContent("正在注册")
            
            var ret = accountObj.save() as Bool
            
            self.hideIndicator()
            if ret == true
            {
                self.loginSuccessForUser(userid, userName: userName)
            }
            else
            {
                self.showHudWithTitle("登录失败")
            }
        }
    }
    
    
    @IBAction func searchBtnClick(sender: AnyObject) {
        searchBar?.hidden = false
        searchBar?.becomeFirstResponder()
    }
    
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        searchBar.hidden = true
        searchBar.resignFirstResponder()
    }
    
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        displayDataSource.removeAllObjects()
//        let arr:NSArray = toDoItems.filteredArrayUsingPredicate(Common.searchResult(searchBar.text))
//        displayDataSource.addObjectsFromArray(arr as [AnyObject])
        toDoItems = NoteDBManger.shareInstance().queryAllNotes()
        var i = 0;
        var arr:NSMutableArray = NSMutableArray()
        while (i < toDoItems.count)
        {
            var note:NoteModel = toDoItems[i] as! NoteModel
            if (note.noteText.componentsSeparatedByString(searchBar.text!).count > 1)
            {
                displayDataSource.addObject(toDoItems[i])
            }
            i++
        }
        
        
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
        var note:NoteModel = displayDataSource[indexPath.row] as! NoteModel
        cell.textLabel!.text = note.noteText
//        var note:NoteModel! = toDoItems.objectAtIndex(indexPath.row) as! NoteModel
//        cell.titleLabel.text = note.noteText
//        cell.timeLabel.text = self.getCreateTimeElapse(note.localCreateTime) as String
        return cell
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return displayDataSource.count
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
        
        var storyBoard: UIStoryboard = self.storyboard!
        
        var detailVC:DetailViewController = storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as! DetailViewController
        var note:NoteModel = displayDataSource[indexPath.row] as! NoteModel
        detailVC.noteId = note.noteId
        
        let appdelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let tempVC:MMDrawerController = appdelegate.window?.rootViewController as! MMDrawerController
        let nav:UINavigationController = tempVC.centerViewController as! UINavigationController
        let masterVC:MasterTableViewController = nav.viewControllers[0] as! MasterTableViewController
        masterVC.showRegist()
        nav.pushViewController(detailVC, animated: true)
    }
}


